package com.whq.knowverywell.business.http;

import org.json.JSONObject;

import android.content.Context;

import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.StringUtil;
import com.whq.knowverywell.util.constant.ErrorCodeConstant;
import com.whq.knowverywell.util.httpclient.HttpResult;

/**
 * 检查返回的结果
 * @author wanghuaiqiang
 *
 */
public class ChkResponseUtil {
	private static final String TAG = "ChkResponseUtil";
	
	/***
	 * 检查返回值是否成功
	 * 并判断是否是需要登出的错误码，如果需要退出，则清空登录信息
	 * @param httpResult
	 * @param context
	 * @return
	 */
	public static boolean chkJsonResponseOk(HttpResult httpResult, Context context) {
		if ( (httpResult == null) 
				|| (!httpResult.checkCode()) 
				) {
			return false;
		}
		
		String responseStr = httpResult.getResp();
		if (StringUtil.isBlank(responseStr)) {
			return false;
		}
		try {
			JSONObject recordJson = new JSONObject(responseStr);
			int resultCode = recordJson.optInt("resultCode", -1);
			if (resultCode == 0) {
				return true;
			} else {
				if (ErrorCodeConstant.SET_LOGOUT_ERROR_CODE.contains(resultCode)) {
					LoginUtil.clearLogin(context);
				}
				
				return false;
			}
		} catch (Exception e) {
			LogUtil.e(TAG, "解析json串出错：", e);
		}
		
		return false;
	}
	
	/**
	 * 判断是否是需要登出的错误码，如果需要退出，则清空登录信息
	 * @param context
	 * @param errorCode
	 * @return
	 */
	public static boolean chkLogoutErrorCode(Context context, Integer errorCode) {
		if (context == null) {
			return false;
		}
		if (ErrorCodeConstant.SET_LOGOUT_ERROR_CODE.contains(errorCode)) {
			LoginUtil.clearLogin(context);
			return true;
		}
		return false;
	}

}
